package com.bycx.dingxinlc.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bycx.core.exception.BusinessException;
import com.bycx.core.startup.AppConfig;
import com.bycx.core.util.HttpHelper;
import com.bycx.core.util.Md5Utils;
import com.bycx.core.util.Page;
import com.bycx.core.util.StringUtils;
import com.bycx.dingxinlc.model.SmsValicode;
import com.bycx.dingxinlc.model.TCustLoginInfo;
import com.bycx.dingxinlc.service.WechatService;
import com.bycx.wechat.util.WeChatSessionUtil;

@Controller
@RequestMapping("/wechat")
public class WechatController {
	private Log log = LogFactory.getLog(WechatController.class);

	@Autowired
	private WechatService wechatService;

	/**
	 * 公众号页面统一入口
	 * 
	 * @Title: enter
	 * @param @param req
	 * @param @param code
	 * @param @param toUrl
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(value = "/enter", method = RequestMethod.GET)
	public String enter(HttpServletRequest req,
			String code,
			String toUrl) {

		log.debug("微信端回调接入：code=" + code + ",toUrl=" + toUrl);

		if (StringUtils.isEmpty(code)) {
			return "";
		}

		WeChatSessionUtil.setCode(code);

		// 获取openid
		// 查询参数
		Map<String, String> params = new HashMap<>();
		params.put("appid", AppConfig.get("wx_appid"));
		params.put("secret", AppConfig.get("wx_appsecret"));
		params.put("code", code);
		params.put("grant_type", "authorization_code");
		// httpclient获取openid
		Map<String, Object> requestByGet = HttpHelper.requestByGet("https://api.weixin.qq.com/sns/oauth2/access_token", params, null);
		Map<String, String> resultMap = JSON.parseObject(StringUtils.replaceBlank(String.valueOf(requestByGet.get(HttpHelper.RESP_STR))), new TypeReference<Map<String, String>>() {
		});
		String openid = resultMap.get("openid");

		log.debug("获取到openid：openid=" + openid);

		WeChatSessionUtil.setOpenId(openid);

		// 查询是否是已绑定用户
		TCustLoginInfo info = wechatService.queryCustLoginInfoByOpenId(openid);
		if (info != null) {
			WeChatSessionUtil.setCustLoginInfo(info);
			return "redirect:" + toUrl;
		} else {
			return "redirect:" + "/wechat/login";
		}
	}

	/**
	 * 登录页面
	 * 
	 * @Title: login
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest req) {
		//if (WeChatSessionUtil.checkLogin())
		//	return "redirect:" + "/wechat/custService/vippay";

		return "wechat/login";
	}

	/** 登录接口 **/
	@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
	@ResponseBody
	public Page<?> doLogin(@RequestBody Page<?> page) {
		String loginType = (String) page.getParam("loginType");
		if (!"1".equals(loginType) && !"2".equals(loginType)) {
			page.setMsg("参数错误！");
			page.setSuccess(false);
			return page;
		}

		String phone = (String) page.getParam("phone");
		if (StringUtils.isEmpty(phone)) {
			page.setMsg("手机号为空！");
			page.setSuccess(false);
			return page;
		} else if (!phone.matches("^1[0-9]{10}$")) {
			page.setMsg("手机号格式错误！");
			page.setSuccess(false);
			return page;
		}

		// 查询用户信息
		TCustLoginInfo loginInfo = wechatService.queryCustLoginInfoByPhoneNo(phone);
		if (loginInfo == null) {
			page.setMsg("该手机号尚未注册！");
			page.setSuccess(false);
			return page;
		}

		// 密码登录
		if ("1".equals(loginType)) {
			String pwd = (String) page.getParam("pwd");
			if (StringUtils.isEmpty(pwd)) {
				page.setMsg("密码为空！");
				page.setSuccess(false);
				return page;
			}
			if (!Md5Utils.encode(Md5Utils.encode(pwd)).equals(loginInfo.getCustPwd())) {
				page.setMsg("密码错误！");
				page.setSuccess(false);
				return page;
			}
		}
		// 验证码登录
		else if ("2".equals(loginType)) {
			SmsValicode smsValicode = WeChatSessionUtil.getSmsValicode();
			if (smsValicode == null) {
				page.setMsg("请先获取验证码！");
				page.setSuccess(false);
				return page;
			}
			String valicode = (String) page.getParam("valicode");
			if (StringUtils.isEmpty(valicode)) {
				page.setMsg("验证码为空！");
				page.setSuccess(false);
				return page;
			}
			if (!smsValicode.validate(phone, valicode)) {
				page.setMsg("验证码不匹配或已过期！");
				page.setSuccess(false);
				return page;
			}
		}

		String openId = WeChatSessionUtil.getOpenId();
		if (StringUtils.isNotEmpty(openId)) {
			// 如果数据库中的openid和当前获取的不一样，就更新
			if (!openId.equals(loginInfo.getOpenId())) {
				wechatService.updateOpenIdById(loginInfo.getId(), openId);
				loginInfo.setOpenId(openId);
				// openid写入会话
				WeChatSessionUtil.setOpenId(openId);
			}
		} else {
			// openid写入会话
			WeChatSessionUtil.setOpenId(loginInfo.getOpenId());
		}

		// 登录信息写入会话
		WeChatSessionUtil.setCustLoginInfo(loginInfo);

		return page;
	}

	/**
	 * 注册页面
	 * 
	 * @Title: reg
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(value = "/reg", method = RequestMethod.GET)
	public String reg(HttpServletRequest req) {
		//if (WeChatSessionUtil.checkLogin())
		//	return "redirect:" + "/wechat/custService/vippay";

		return "wechat/reg";
	}

	/** 注册接口 */
	@RequestMapping(value = "/doReg", method = RequestMethod.POST)
	@ResponseBody
	public Page<?> doReg(@RequestBody Page<?> page) {
		String phone = (String) page.getParam("phone");
		if (StringUtils.isEmpty(phone)) {
			page.setMsg("手机号为空！");
			page.setSuccess(false);
			return page;
		} else if (!phone.matches("^1[0-9]{10}$")) {
			page.setMsg("手机号格式错误！");
			page.setSuccess(false);
			return page;
		}

		TCustLoginInfo info = wechatService.queryCustLoginInfoByPhoneNo(phone);
		if (info != null) {
			page.setMsg("该手机号已被注册！");
			page.setSuccess(false);
			return page;
		}

		SmsValicode smsValicode = WeChatSessionUtil.getSmsValicode();
		if (smsValicode == null) {
			page.setMsg("请先获取验证码！");
			page.setSuccess(false);
			return page;
		}
		String valicode = (String) page.getParam("valicode");
		if (StringUtils.isEmpty(valicode)) {
			page.setMsg("验证码为空！");
			page.setSuccess(false);
			return page;
		}
		if (!smsValicode.validate(phone, valicode)) {
			page.setMsg("验证码不匹配或已过期！");
			page.setSuccess(false);
			return page;
		}

		String pwd = (String) page.getParam("pwd");
		if (StringUtils.isEmpty(pwd)) {
			page.setMsg("密码为空！");
			page.setSuccess(false);
			return page;
		} else if (pwd.length() < 6) {
			page.setMsg("密码至少6位！");
			page.setSuccess(false);
			return page;
		}

		try {
			// 注册
			TCustLoginInfo loginInfo = wechatService.doReg(phone, pwd, WeChatSessionUtil.getOpenId());
			// 登录
			WeChatSessionUtil.setCustLoginInfo(loginInfo);

			return page;
		} catch (BusinessException e) {
			page.setMsg(e.getMessage());
			page.setCode(e.getCode());
			page.setSuccess(false);
			return page;
		}
	}

	/**
	 * 发送短信验证码
	 * 
	 * @Title: sendSmsValicode
	 * @param @param req
	 * @param @return 参数
	 * @return Object 返回类型
	 * @throws
	 */
	@RequestMapping(value = "/smsValicode", method = RequestMethod.POST)
	@ResponseBody
	public Page<?> sendSmsValicode(HttpServletRequest req,
			@RequestBody Page<?> page) {
		String phone = (String) page.getParam("phone");
		if (StringUtils.isEmpty(phone)) {
			page.setSuccess(false);
			page.setMsg("手机号为空！");
			return page;
		}

		// 类型标识
		String type = (String) page.getParam("type");
		// 登录
		if ("login".equals(type)) {
			// 查询用户信息
			TCustLoginInfo loginInfo = wechatService.queryCustLoginInfoByPhoneNo(phone);
			if (loginInfo == null) {
				page.setMsg("该手机号尚未注册！");
				page.setSuccess(false);
				return page;
			}
		}
		// 注册
		else if ("reg".equals(type)) {
			// 查询用户信息
			TCustLoginInfo loginInfo = wechatService.queryCustLoginInfoByPhoneNo(phone);
			if (loginInfo != null) {
				page.setMsg("该手机号已被注册！");
				page.setSuccess(false);
				return page;
			}
		}
		// 找回密码
		else if ("find".equals(type)) {
			// 查询用户信息
			TCustLoginInfo loginInfo = wechatService.queryCustLoginInfoByPhoneNo(phone);
			if (loginInfo == null) {
				page.setMsg("该手机号尚未注册！");
				page.setSuccess(false);
				return page;
			}
		} else {
			page.setMsg("参数错误！");
			page.setSuccess(false);
			return page;
		}

		try {
			boolean success = wechatService.sendSmsValicode(phone);
			page.setSuccess(success);
			if (!success)
				page.setMsg("验证码发送失败！");
		} catch (Exception e) {
			page.setMsg("验证码发送失败！");
			page.setSuccess(false);
		}

		return page;
	}
	
	/**
	 * 校验短信验证码
	 * 
	 * @Title: checkSmsValicode
	 * @param @param req
	 * @param @return 参数
	 * @return 
	 * @throws
	 */
	@RequestMapping(value = "/checkValicode", method = RequestMethod.POST)
	@ResponseBody
	public Page<?> checkSmsValicode(@RequestBody Page<?> page) {
		String phone = (String) page.getParam("phone");
		
		SmsValicode smsValicode = WeChatSessionUtil.getSmsValicode();
		if (smsValicode == null) {
			page.setMsg("请先获取验证码！");
			page.setSuccess(false);
			return page;
		}
		String valicode = (String) page.getParam("valicode");
		if (StringUtils.isEmpty(valicode)) {
			page.setMsg("验证码为空！");
			page.setSuccess(false);
			return page;
		}
		if (!smsValicode.validate(phone, valicode)) {
			page.setMsg("验证码不匹配或已过期！");
			page.setSuccess(false);
			return page;
		}
		
		return page;
	}

	/**
	 * 找回密码
	 * 
	 * @Title: find
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@RequestMapping(value = "/find", method = RequestMethod.GET)
	public String find(HttpServletRequest req) {
		return "wechat/find";
	}

	/** 找回密码接口 */
	@RequestMapping(value = "/doFind", method = RequestMethod.POST)
	@ResponseBody
	public Page<?> doFind(@RequestBody Page<?> page) {
		String phone = (String) page.getParam("phone");
		if (StringUtils.isEmpty(phone)) {
			page.setMsg("手机号为空！");
			page.setSuccess(false);
			return page;
		} else if (!phone.matches("^1[0-9]{10}$")) {
			page.setMsg("手机号格式错误！");
			page.setSuccess(false);
			return page;
		}

		TCustLoginInfo info = wechatService.queryCustLoginInfoByPhoneNo(phone);
		if (info == null) {
			page.setMsg("该手机号尚未注册！");
			page.setSuccess(false);
			return page;
		}

		/*SmsValicode smsValicode = WeChatSessionUtil.getSmsValicode();
		if (smsValicode == null) {
			page.setMsg("请先获取验证码！");
			page.setSuccess(false);
			return page;
		}
		String valicode = (String) page.getParam("valicode");
		if (StringUtils.isEmpty(valicode)) {
			page.setMsg("验证码为空！");
			page.setSuccess(false);
			return page;
		}
		if (!smsValicode.validate(phone, valicode)) {
			page.setMsg("验证码不匹配或已过期！");
			page.setSuccess(false);
			return page;
		}*/

		String pwd = (String) page.getParam("pwd");
		if (StringUtils.isEmpty(pwd)) {
			page.setMsg("密码为空！");
			page.setSuccess(false);
			return page;
		} else if (pwd.length() < 6) {
			page.setMsg("密码至少6位！");
			page.setSuccess(false);
			return page;
		}

		try {
			// 找回密码
			wechatService.doFind(phone, pwd);
			// 登录
			WeChatSessionUtil.setCustLoginInfo(info);

			return page;
		} catch (BusinessException e) {
			page.setMsg(e.getMessage());
			page.setCode(e.getCode());
			page.setSuccess(false);
			return page;
		}
	}
}
